<?php
declare(strict_types=1);


namespace App\Fastapp\Mapper;

use App\Fastapp\Model\FastappAd;
use App\Fastapp\Model\FastappArticle;
use Hyperf\Database\Model\Builder;
use Mine\Abstracts\AbstractMapper;

/**
 * 广告列表Mapper类
 */
class FastappAdMapper extends AbstractMapper
{
    /**
     * @var FastappAd
     */
    public $model;

    public function assignModel()
    {
        $this->model = FastappAd::class;
    }

    /**
     * 搜索处理器
     * @param Builder $query
     * @param array $params
     * @return Builder
     */
    public function handleSearch(Builder $query, array $params): Builder
    {

        // 开始时间
        if (isset($params['start_at']) && filled($params['start_at'])) {
            $query->where('start_at', '=', $params['start_at']);
        }

        // 结束时间
        if (isset($params['end_at']) && filled($params['end_at'])) {
            $query->where('end_at', '=', $params['end_at']);
        }

        // 永久
        if (isset($params['fixed']) && filled($params['fixed'])) {
            $query->where('fixed', '=', $params['fixed']);
        }

        // 调用代码
        if (isset($params['code']) && filled($params['code'])) {
            $query->where('code', '=', $params['code']);
        }

        return $query->orderByDesc('id');
    }

    public function objectData(int $type): array
    {
        if ($type == 4) {
            return FastappArticle::query()->select(['id', 'title'])->get()->map(function ($item) {
                return [
                    'id' => $item->id,
                    'name' => fastapp_lang_text($item->title)
                ];
            })->toArray();
        } else if ($type == 6) {
            if (class_exists('\App\Game\Model\Game'))
                return \App\Game\Model\Game::query()->select(['id', 'name'])->get()->map(function ($item) {
                    return [
                        'id' => $item->id,
                        'name' => fastapp_lang_text($item->name)
                    ];
                })->toArray();
        }
        return [];
    }

    public function list(): array
    {
        return $this->model::query()->select(['id', 'name'])->get()->toArray();
    }
}